package godau.fynn.bandcampdirect.activity.fragment;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import godau.fynn.bandcampdirect.R;
import godau.fynn.bandcampdirect.bandcamp.Bandcamp;
import godau.fynn.bandcampdirect.bandcamp.Giftcard;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

public class GiftcardFragment extends Fragment {

    private TextView resultView;
    private Button validate;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_giftcard, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        Giftcard giftcard = new Bandcamp(null).buildGiftcard();

        resultView = view.findViewById(R.id.giftcard_result);
        validate = view.findViewById(R.id.redeem);
        EditText editText = view.findViewById(R.id.edit);

        validate.setOnClickListener((clickedView) -> {
            validate.setEnabled(false);
            resultView.setVisibility(View.GONE);

            new Thread(() -> {

                try {
                    JSONObject response = giftcard.getData(editText.getText().toString());
                    boolean ok = response.getBoolean("ok");

                    if (ok) {
                        // Display available card data
                        JSONObject cardData = response.getJSONObject("card_data");
                        JSONObject value = cardData.getJSONObject("value");

                        String currency = value.getString("currency");
                        int amount = value.getInt("amount") / 100; // bc doesn't support card of a value % 100 != 0

                        String senderName = cardData.getString("sender_name");
                        String senderEmail = cardData.getString("email");
                        String id = cardData.getString("card_id");
                        boolean hasNote = !response.getJSONObject("card_data")
                                .isNull("sender_note");

                        final String note = hasNote ? cardData.getString("sender_note") : null;

                        boolean redeemed = !giftcard.isValid(editText.getText().toString());

                        new Handler(Looper.getMainLooper()).post(() -> setResult(
                                "You gift card is valid" +
                                        (redeemed? ", but it has already been redeemed" : "")
                                        + ". Its ID is " + id + "."
                                        + "\n\n"
                                        + "It " +
                                        (redeemed? "was" : "is")
                                        + " worth " + amount + " " + currency + " and " +
                                        (redeemed? "has been" : "was")
                                        + " sent by "
                                        + senderName + " <" + senderEmail + ">" +
                                        (hasNote ? ", who " +
                                                (redeemed? "had " : "")
                                                + "attached the following note:\n\n" + note : ".")
                                )
                        );

                        String image = cardData.getString("img_src");
                        loadImage("https://bandcamp.com" + image, view.findViewById(R.id.giftcard));

                    } else {
                        // Display error
                        String error = response.getString("error");

                        new Handler(Looper.getMainLooper()).post(() -> setResult(
                                        error.equals("alreadyRedeemed") ?
                                                R.string.giftcard_invalid_redeemed
                                                : R.string.giftcard_invalid
                                )
                        );
                    }

                } catch (IOException | JSONException e) {
                    new Handler(Looper.getMainLooper()).post(() -> setResult(R.string.giftcard_test_no_network)
                    );
                    e.printStackTrace();
                }
            }).start();
        });

    }

    private void setResult(@StringRes int text) {
        setResult(resultView.getContext().getString(text));
    }

    private void setResult(String text) {
        resultView.setVisibility(View.VISIBLE);
        resultView.setText(text);
        validate.setEnabled(true);
    }

    private void loadImage(String url, ImageView image) {
        try {
            InputStream imageStream = new OkHttpClient().newCall(
                    new Request.Builder()
                            .url(url)
                            .build()
            ).execute().body().byteStream();

            BitmapDrawable bitmapDrawable = new BitmapDrawable(image.getResources(), imageStream);
            new Handler(Looper.getMainLooper()).post(() -> {
                image.setImageDrawable(bitmapDrawable);
                image.setVisibility(View.VISIBLE);
            });
        } catch (IOException | IllegalArgumentException e) {
            // Doesn't matter, don't display image then
            e.printStackTrace();
        }
    }
}
